/*
	投票前端js
	base on laytpl、jQuery
*/

/**

 @Name : laytpl v1.2 - 精妙的JavaScript模板引擎
 @Author: 贤心
 @Date: 2014-10-27
 @Site：http://sentsin.com/layui/laytpl
 @License：MIT

 */

;
! function() {
	"use strict";

	var config = {
		open: '{{',
		close: '}}'
	};

	var tool = {
		exp: function(str) {
			return new RegExp(str, 'g');
		},
		//匹配满足规则内容
		query: function(type, _, __) {
			var types = [
				'#([\\s\\S])+?', //js语句
				'([^{#}])*?' //普通字段
			][type || 0];
			return exp((_ || '') + config.open + types + config.close + (__ || ''));
		},
		escape: function(html) {
			return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
				.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');
		},
		error: function(e, tplog) {
			var error = 'Laytpl Error：';
			typeof console === 'object' && console.error(error + e + '\n' + (tplog || ''));
			return error + e;
		}
	};

	var exp = tool.exp,
		Tpl = function(tpl) {
			this.tpl = tpl;
		};

	Tpl.pt = Tpl.prototype;

	window.errors = 0;

	//编译模版
	Tpl.pt.parse = function(tpl, data) {
		var that = this,
			tplog = tpl;
		var jss = exp('^' + config.open + '#', ''),
			jsse = exp(config.close + '$', '');

		tpl = tpl.replace(/\s+|\r|\t|\n/g, ' ').replace(exp(config.open + '#'), config.open + '# ')

			.replace(exp(config.close + '}'), '} ' + config.close).replace(/\\/g, '\\\\')

			.replace(/(?="|')/g, '\\').replace(tool.query(), function(str) {
				str = str.replace(jss, '').replace(jsse, '');
				return '";' + str.replace(/\\/g, '') + ';view+="';
			})

			.replace(tool.query(1), function(str) {
				var start = '"+(';
				if (str.replace(/\s/g, '') === config.open + config.close) {
					return '';
				}
				str = str.replace(exp(config.open + '|' + config.close), '');
				if (/^=/.test(str)) {
					str = str.replace(/^=/, '');
					start = '"+_escape_(';
				}
				return start + str.replace(/\\/g, '') + ')+"';
			});

		tpl = '"use strict";var view = "' + tpl + '";return view;';
		//console.log(tpl);

		try {
			that.cache = tpl = new Function('d, _escape_', tpl);
			return tpl(data, tool.escape);
		} catch (e) {
			delete that.cache;
			return tool.error(e, tplog);
		}
	};

	Tpl.pt.render = function(data, callback) {
		var that = this,
			tpl;
		if (!data) return tool.error('no data');
		tpl = that.cache ? that.cache(data, tool.escape) : that.parse(that.tpl, data);
		// console.log()
		if (!callback) return tpl;
		callback(tpl);
	};

	var laytpl = function(tpl) {
		if (typeof tpl !== 'string') return tool.error('Template not found');
		return new Tpl(tpl);
	};

	laytpl.config = function(options) {
		options = options || {};
		for (var i in options) {
			config[i] = options[i];
		}
	};

	laytpl.v = '1.2';

	/* istanbul ignore next */
	"function" == typeof define ? define(function() {
		return laytpl
	}) : "undefined" != typeof exports ? module.exports = laytpl : window.laytpl = laytpl

}();

;
! function() {
	"use strict";
	var voteTmpl = (function() {
		/*!
    <div style="display:none;">hack IE<style>
  .votecontainer ul,li { margin:0; padding:0; }
  .votecontainer{ font-size:12px;	padding:0 5px; margin:auto; max-width:680px; text-align:left; }
  .votecontainer .vote-title { text-align:center; margin:0; }
  .vote-content {}
  .vote-subject { padding:3px; }
  .subject { font-size:12px; font-weight:bold;}
  .require { color:red;  font-weight:normal; }
  .rules { font-weight:normal; }
  .subject-items { list-style:none; }
  .item {  margin:0; display:list-item;text-align:-webkit-match-parent; }

  .item input{ margin-right:8px; }
  .vote_btnrow { margin:0 auto; padding:10px; text-align:center; }
  .votecontainer img{	_width:expression(Math.min(120,this.width));  border:0; }
  </style>
  <!--具体映射关系参照代码类别voteItemType
  item_0:选择
  item_1:单行文本
  item_2:多行文本
  item_3:图片上传
  item_4:文章列表
  -->
  </div>
    <div class="vote-wrap">
    <div id='vote_{{d.ID}}' class='votecontainer'>
    <h1 class="vote-title">欢迎参与调查:{{d.title}}</h1>
    <div id="replacer_voteForm_{{d.ID}}" action="#" method="post" target="_blank">
    <input type='hidden' id='ID' name='ID' value='{{d.ID}}' />
    <input type='hidden' id='siteID' name='siteID' value='{{d.siteID}}' />
    <div class="vote-content">
    {{# $.each(d.voteSubject,function(idx,voteSubject){ }}
      <div class="vote-subject">
        <h5 class="subject-title">
          <span class="subject">{{d.voteSubject.length>1 ? (idx + 1) + '.' : ''}} {{voteSubject.subject}}</span>
        </h5>
        <ul class="subject-items">
          {{# $.each(voteSubject.voteItem,function(voteItemIdx,voteItem){ }}
            <li class="item">
              {{# if(voteSubject.type=='S' || voteSubject.type=='D'){ }}
              <label><input type="{{voteSubject.type=='S'?'radio':'checkbox'}}" name="Subject_{{voteItem.subjectID}}" value="{{voteItem.ID}}" />{{voteItem.item}}</label>
              {{# } }}
              {{# if(voteSubject.type=='W'){ }}
                <input name="Write_Subject_{{voteSubject.ID}}" type="hidden" value="{{voteItem.ID}}" />
                {{# if(voteItem.itemType=='1') { }}
                  <input type="text" id="Subject_{{voteItem.subjectID}}" name="Subject_{{voteItem.subjectID}}" style="width:100%;" verify="Regex=[\w\W]{0,120}&&NotNull" />
                {{# } else { }}
                  <textarea style="height:60px;width:100%;vertical-align:top;" id="Subject_{{voteItem.subjectID}}"  name="Subject_{{voteItem.subjectID}}" verify="Regex=[\w\W]{0,400}&&NotNull"></textarea>
                {{# } }}
              {{# } }}
              {{# if(voteSubject.type=='I'){ }}
                <label>
                  <input name="Subject_{{voteItem.subjectID}}" type="checkbox" value="{{voteItem.ID}}" />
                  {{# if(voteItem.imageInfo!=null){ }}
                  	{{voteItem.imageInfo}}
                  {{# } }}
                </label>
                <p>
                  {{# if(voteItem.linkURL!=null && voteItem.linkURL!=''){ }}
                  <a href="{{typeof voteItem.previewURL === 'string'?voteItem.previewURL:voteItem.linkURL}}" target="_blank">
                    <img src="{{voteItem.imagePath?voteItem.imagePath:voteItem.item}}"/>
                  </a>
                  {{# } else { }}
                  <img src="{{voteItem.imagePath?voteItem.imagePath:voteItem.item}}"/>
                  {{# } }}
                </p>
               {{# } }}
               {{# if(voteSubject.type=='A'){ }}
                <label>
                  <input name="Subject_{{voteItem.subjectID}}" type="checkbox" value="{{voteItem.ID}}" />
                  {{voteItem.item}}
                </label>
                {{voteItem.summary?voteItem.summary:''}}<a href="{{typeof voteItem.previewURL === 'string'?voteItem.previewURL:voteItem.linkURL}}" target="_blank">查看详细>></a>
              {{# } }}
            </li>
          {{# }); }}
        </ul>
      </div>
      {{# }); }}
    </div>
    <div class="vote_btnrow">
      {{# if(d.verifyFlag=='Y'){ }}
      <span class="vote-authcode">
        验证码
        <input name="vote_VerifyCode" type="text" style="width:60px" id="vote_VerifyCode" class="inputText" onfocus="this.select();" />&nbsp;
        <img src="{{frontAppContext }}authCode.png" alt="点击刷新验证码"
          height="30" align="absmiddle" style="cursor:pointer;"
          onClick='this.src="{{frontAppContext}}authCode.png?"+new Date().getTime()' />
      </span>
      {{# } }}
      <span class="vote-submit">
      <input id="tijiao" type="button" value="提交" onclick="submitVote()" class="btn btn-primary">&nbsp;&nbsp;
      </span>
      {{# if(d.showResult){ }}
      <span class="vote-viewresult" >
      <input type='button' value="查看" onclick='javascript:window.open("{{siteURL || ''}}vote/vote_result.shtml?ID={{d.ID}}&SiteID={{d.siteID}}&View=true")' class="btn btn-default" />
      </span>
      {{# } }}
    </div>
    </div>
  </div></div>
  <script>
	function submitVote(){
    var dc = Form.getData("voteForm_{{d.ID}}");
    $.ajax({
      type:'POST',
      url:'{{d.frontAppContext}}front/votes/{{d.ID}}',
      data:dc,
      xhrFields: {
        withCredentials: true
      },
      success:function(response) {
        Dialog.alert(response.message, function () {
          if(response.status === 1) {
            window.open("{{siteURL || ''}}vote/vote_result.shtml?ID={{d.ID}}&SiteID={{d.siteID}}&View=true");
          }
        });
      }
    })
  }
  (function () {
    var formReplacer = document.getElementById('replacer_voteForm_{{d.ID}}');
    var inForm = false;
    var ele = formReplacer.parentNode;
    var body = document.body;
    while (ele !== body) {
      if (ele.tagName === 'FORM') {
        inForm = true;
        break;
      }
      ele = ele.parentNode;
    }
    ele = null;
    if (!inForm) {
      var form = document.createElement('form');
      form.setAttribute('action', formReplacer.getAttribute('action'));
      form.setAttribute('target', formReplacer.getAttribute('target'));
      form.setAttribute('method', formReplacer.getAttribute('method'));
      form.id = 'voteForm_{{d.ID}}';
      formReplacer.parentNode.insertBefore(form, formReplacer);
      form.appendChild(formReplacer);
    }

    var container = document.getElementById('vote_{{d.ID}}'),
    inputs = container.getElementsByTagName('input'),
    textareas = container.getElementsByTagName('textarea'),
    maxNumForInput = 120,
    maxNumForTextarea = 400,
    i,
    len;

    for ((i = 0, len = inputs.length); i < len; i++) {
      if (inputs[i].type === 'text' || inputs[i].type === 'password') {
        inputs[i].setAttribute('maxlength', maxNumForInput);
      }
    }
    var lenControl = function (evt) {
      evt = evt || window.event;
      if (this.value.length > maxNumForTextarea) {
        return false;
      }
    },
    blurHandler = function (evt) {
      if (this.value.length > maxNumForTextarea) {
        this.value = this.value.substring(0, maxNumForTextarea);
      }
    };
    for ((i = 0, len = textareas.length); i < len; i++) {
      textareas[i].onkeydown = lenControl;
      textareas[i].onblur = blurHandler;
    }

		$("#voteForm_{{d.ID}}").children().keydown(function(event){
			 event = event ? event: window.event;
			 if(event.keyCode == 13){
			   submitVote();
				 return false;
			 }
	 });

  })();

  </script>

    */
	}).toString().match(/\/\*!([\s\S]+)\*\//)[1];

	var Vote = {
		tmpl: null,
		jsPath: function() {
			var jsPath = document.currentScript ? document.currentScript.src : function() {
				var js = document.scripts,
					last = js.length - 1,
					src;
				for (var i = last; i > 0; i--) {
					if (js[i].readyState === 'interactive') {
						src = js[i].src;
						break;
					}
				}
				return src || js[last].src;
			}();
			return jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
		}(),
		jsonData: null,
		loadJS: function(url, onsuccess) {
			var head = document.getElementsByTagName('head')[0] || document.documentElement,
				script = document.createElement('script'),
				done = false;
			script.src = url;
			script.onerror = script.onload = script.onreadystatechange = function() {
				if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
					done = true;
					if (onsuccess) {
						onsuccess();
					}
					script.onerror = script.onload = script.onreadystatechange = null;
					//head.removeChild(script);
				}
			};
			head.appendChild(script);
		},
		init: function() {
			var self = this;
			var path = this.jsPath;
			// 依赖jQuery，加载voteFront.js同目录的zcms_common.min.js，该js中打包了jQuery,项目实施中也可根据需要单独替换成网站目录中的jQuery文件路径
			if (typeof jQuery === 'undefined') {
				this.loadJS(path + 'zcms_common.min.js', function() {
					self.loadVoteData();
				});
			} else {
				this.loadVoteData();
			}
		},
		// 加载json文件并结合模板进行渲染
		loadVoteData: function() {
			var self = this;
			var dataPath = this.getDataPath();
			if (dataPath !== null) {
				$.getJSON(dataPath, function(res) {
					res = res.data ? res.data : res;
					self.dealData(res);
				})
			}
		},
		dealData: function(res) {
			this.tmpl = voteTmpl;
			if (window.Zving && window.Zving.CONTEXTPATH) {
				res.frontAppContext = Zving.CONTEXTPATH
			} else if (window._cmsdata_frontAppContext) {
				res.frontAppContext = window._cmsdata_frontAppContext;
			}
			this.jsonData = res;
			this.render();
		},
		render: function() {
			var self = this;
			laytpl(this.tmpl).render(self.jsonData, function(html) {
				$("#votejs_" + self.jsonData.ID).html(html)
			});
		},
		getDataPath: function() {
			var scripts = document.getElementsByTagName('script'),
				script = document.currentScript || scripts[scripts.length - 1];
			var dataPath = script.getAttribute('data');
			return dataPath;
		}
	};

	Vote.init();

}();
